const BaseHandler     = require('../base-handler');
const HTTP_VERBS      = require('../../../constants').HTTP_VERBS;

class WeChatUserAuthorizeHandler extends BaseHandler {

    get pattern() {
        return "/wall/:wall_id/authorize";
    }

    doGET(request, response) {
        var params = request.params;
        var query = request.query;
        var session = request.session;
        if(!request.session.walls[params.wall_id]) {
            request.session.walls[params.wall_id] = {};
        }
        if(!query.code) {
            if(query.anonymous_user_id) {
                request.session.walls[params.wall_id].is_anonymous = true;
                request.session.walls[params.wall_id].is_wechat = session.is_wechat;
                request.session.walls[params.wall_id].wall_user_id = query.anonymous_user_id;
                response.redirect('/wall/' + params.wall_id + "?tried=true");
            } else {
                response.redirect('/wall/' + params.wall_id);
            }
        } else {
            this.Controller.handleWeChatUserAuthorization(request.query.code, params.wall_id, session.walls[params.wall_id].wall_user_id, (result) => {
                if(result.success) {
                    request.session.walls[params.wall_id].is_anonymous = result.data.is_anonymous;
                    request.session.walls[params.wall_id].is_wechat = session.is_wechat;
                    request.session.walls[params.wall_id].wall_user_id = result.data.wall_user_id;
                    response.redirect('/wall/' + request.params.wall_id + "?tried=true");
                } else {
                    var errno = result.error.errno;
                    switch(errno) {
                    case 61007:
                        response.end('系统暂时不可用，请稍后再试！'); //TODO: Should render a beautiful error page here
                        break;
                    default:
                        response.end('系统暂时不可用，请稍后再试！');
                    }
                }
            });
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
    }
}

module.exports = WeChatUserAuthorizeHandler;